package com.southminority.ethnic.controller.admin.contact;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.service.contact.CooperationFileService;
import com.southminority.ethnic.controller.contact.vo.CooperationFileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 合作申请文件管理端控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "🛠️ 合作申请文件管理后台", description = "管理员上传、更新、删除合作申请文件的后台接口")
@RestController
@RequestMapping("/admin/cooperation-files")
@CrossOrigin
public class CooperationFileAdminController {

    private final CooperationFileService cooperationFileService;

    public CooperationFileAdminController(CooperationFileService cooperationFileService) {
        this.cooperationFileService = cooperationFileService;
    }

    /**
     * 获取所有文件列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取所有合作申请文件列表", description = "获取所有合作申请文件的列表，不分页")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<List<CooperationFileVO>> getFileList() {
        try {
            List<CooperationFileVO> files = cooperationFileService.getAllFiles();
            return R.ok(files);
        } catch (Exception e) {
            log.error("获取合作申请文件列表失败", e);
            return R.fail("获取文件列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取文件详情
     */
    @GetMapping("/detail/{id}")
    @Operation(summary = "获取文件详情", description = "根据文件ID获取合作申请文件的详细信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "404", description = "文件不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<CooperationFileVO> getFileDetail(
            @Parameter(description = "文件ID", required = true, example = "1") @PathVariable Long id) {
        try {
            CooperationFileVO file = cooperationFileService.getFileDetailAdmin(id);
            if (file == null) {
                return R.fail("文件不存在");
            }
            return R.ok(file);
        } catch (Exception e) {
            log.error("获取文件详情失败: id={}", id, e);
            return R.fail("获取文件详情失败: " + e.getMessage());
        }
    }

    /**
     * 上传合作申请文件
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传合作申请文件", description = "上传新的合作申请文件，支持PDF、Word等格式")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "上传成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误或文件为空"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<CooperationFileVO> uploadFile(
            @Parameter(description = "要上传的文件", required = true) @RequestParam("file") MultipartFile file,
            @Parameter(description = "文件标题", required = true, example = "项目合作申请表") @RequestParam("title") String title,
            @Parameter(description = "文件描述", example = "最新版的项目合作申请表") @RequestParam(value = "description", required = false) String description,
            @Parameter(description = "版本号", example = "v1.1") @RequestParam(value = "version", defaultValue = "v1.0") String version,
            @Parameter(description = "是否设为默认文件", example = "true") @RequestParam(value = "isDefault", defaultValue = "false") Boolean isDefault) {
        try {
            CooperationFileVO result = cooperationFileService.uploadFile(file, title, description, version, isDefault);
            log.info("upload success: id={}", result.getId());
            return R.ok(result);
        } catch (Exception e) {
            log.error("upload failed", e);
            return R.fail("上传失败: " + e.getMessage());
        }
    }

    /**
     * 更新文件信息
     */
    @PutMapping("/update/{id}")
    @Operation(summary = "更新文件信息", description = "更新合作申请文件的标题、描述、版本等元数据")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "404", description = "文件不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<CooperationFileVO> updateFile(
            @Parameter(description = "文件ID", required = true, example = "1") @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "要更新的文件信息", required = true, 
                content = @Content(schema = @Schema(implementation = CooperationFileVO.class)))
            @org.springframework.web.bind.annotation.RequestBody CooperationFileVO fileVO) {
        try {
            CooperationFileVO result = cooperationFileService.updateFile(id, fileVO);
            if (result == null) {
                return R.fail("文件不存在");
            }
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新文件信息失败: id={}", id, e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除文件", description = "从服务器删除合作申请文件（物理删除）")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "404", description = "文件不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<Void> deleteFile(@Parameter(description = "文件ID", required = true, example = "1") @PathVariable Long id) {
        try {
            boolean success = cooperationFileService.deleteFile(id);
            if (success) {
                return R.ok();
            } else {
                return R.fail("文件不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("删除文件失败: id={}", id, e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除文件
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除文件", description = "批量删除多个合作申请文件")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<String> batchDeleteFiles(@org.springframework.web.bind.annotation.RequestBody List<Long> ids) {
        try {
            int deletedCount = cooperationFileService.batchDeleteFiles(ids);
            return R.ok("成功删除 " + deletedCount + " 个文件");
        } catch (Exception e) {
            log.error("批量删除文件失败: ids={}", ids, e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 设置/取消默认文件
     */
    @PutMapping("/set-default/{id}")
    @Operation(summary = "设置/取消默认文件", description = "将指定文件设置为默认文件或取消默认状态")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "操作成功"),
        @ApiResponse(responseCode = "404", description = "文件不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<String> setDefaultFile(
            @Parameter(description = "文件ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "是否设为默认：1-设为默认，0-取消默认", required = true, example = "1") 
            @RequestParam Integer isDefault) {
        try {
            boolean success = cooperationFileService.setDefaultFile(id, isDefault == 1);
            if (success) {
                return R.ok(isDefault == 1 ? "设置成功" : "取消成功");
            } else {
                return R.fail("文件不存在或操作失败");
            }
        } catch (Exception e) {
            log.error("设置默认文件失败: id={}, isDefault={}", id, isDefault, e);
            return R.fail("操作失败: " + e.getMessage());
        }
    }

    /**
     * 更新文件状态
     */
    @PutMapping("/status/{id}")
    @Operation(summary = "更新文件状态", description = "更新文件的状态（启用/禁用）")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "404", description = "文件不存在"),
        @ApiResponse(responseCode = "401", description = "未登录或token无效"),
        @ApiResponse(responseCode = "403", description = "无管理员权限")
    })
    public R<String> updateFileStatus(
            @Parameter(description = "文件ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "状态值：1-启用，0-禁用", required = true, example = "0",
                schema = @Schema(allowableValues = {"1", "0"})) @RequestParam Integer status) {
        try {
            boolean success = cooperationFileService.updateFileStatus(id, status);
            if (success) {
                return R.ok("状态更新成功");
            } else {
                return R.fail("文件不存在或更新失败");
            }
        } catch (Exception e) {
            log.error("更新文件状态失败: id={}, status={}", id, status, e);
            return R.fail("更新状态失败: " + e.getMessage());
        }
    }


} 
